<?php
/**
 * 配置站点 - 功能参数
 */

namespace PKApp\Admin;

use PKCommon\Controller\AdminController;
use PKFrame\DataHandler\Arrays;

class AdminConfig extends AdminController
{

    public function Main()
    {
        $this->fetch('admin_config');
    }

    public function ApiGetDetail()
    {
        $listDict_config = dict('funcConfig');
        $result = [];
        if (is_array($listDict_config)) {
            foreach ($listDict_config as $key => $item) {
                $result[$key] = $this->readConfigFileName($key);
            }
        }
        $this->json($result);
    }

    public function ApiByCreate()
    {
        $listDict_config = dict('funcConfig');
        if (is_array($listDict_config)) {
            foreach ($listDict_config as $key => $item) {
                if (array_key_exists($key, $listDict_config) && is_array($item)) {
                    $this->_putDiskConfig($item, $key);
                }
            }
        }
        $this->json();
    }

    /**
     * 遍历所有站点提取其语言与语言对应的存放路径
     * @return array
     */
    private function _configOfIsAutoSwitchAccorToIP(): array
    {
        $list_site = $this->serviceOfSite()->GetList([], ['id', 'setting', 'Site_Path']);
        $listLang_site = [];
        foreach ($list_site as $item) {
            $setting = Arrays::Unserialize($item['setting']);
            $listLang_site[$item['id']] = [
                'lang' => $setting['Default_Lang'],
                'path' => trim($item['Site_Path'])];
        }
        return $listLang_site;
    }

    private function _putDiskConfig(array $dict_configParams, string $params_prefix)
    {
        $list_save = [];
        $list_post = request()->post($params_prefix);
        if (Arrays::Is($list_post))
            foreach ($dict_configParams as $item_field) {
                if (is_array($list_post) && array_key_exists($item_field, $list_post)) {
                    if ($item_field == 'isAutoSwitchAccorToIP') {
                        $list_save['list_site'] = $this->_configOfIsAutoSwitchAccorToIP();
                    }
                    $list_save[$item_field] = $list_post[$item_field];
                }
            }
        cache()->Disk()->WriteByConfig($this->configFileName($params_prefix), $list_save);
    }
}